<?php
/**
 * This file is form http://findcat.cn
 *
 * @link     https://findcat.cn
 * @email    1476982312@qq.com
 */
namespace App\Http\Middleware;

use Closure;
use App\Models\Article;
use App\Models\Website;
use App\Models\Category;
use App\Models\FriendlyLink;
use Illuminate\Support\Facades\Cache;

class UseCache
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $menu           = Cache::get('menu');
        $webSite        = Cache::get('web_site');
        $friendlyLink   = Cache::get('friendly_link');
        $article        = Cache::get('article');
        $todayRecommend = Cache::get('today_recommend');
        $bannerArticle  = Cache::get('banner_article');

        if (empty($menu)) {
            $menu = Category::query()
                ->where('p_id', 0)
                ->orderBy('sort', 'asc')
                ->pluck('name', 'id');

            Cache::forever('menu', $menu);
        }

        if (empty($webSite)) {
            $webSite = Website::query()
                ->where('status', true)
                ->orderBy('sort', 'asc')
                ->get();

            Cache::forever('web_site', $webSite);
        }

        if (empty($friendlyLink)) {
            $friendlyLink = FriendlyLink::query()
                ->where('status', true)
                ->orderBy('sort', 'asc')
                ->get();

            Cache::forever('friendly_link', $friendlyLink);
        }

        if (empty($article)) {
            $article = Article::query()
                ->where('id','!=', 7)
                ->where('status', true)
                ->orderByDesc('click')
                ->limit(10)
                ->get();

            Cache::forever('article', $article);
        }

        if (empty($todayRecommend)) {
            $todayRecommend = Article::query()
                ->where('id','!=', 7)
                ->where('status', true)
                ->inRandomOrder()
                ->first();

            Cache::forever('today_recommend', $todayRecommend);
        }

        if (empty($bannerArticle)) {
            $bannerArticle = Article::query()
                ->where('id','!=', 7)
                ->where('status', true)
                ->inRandomOrder()
                ->limit(3)
                ->get();

            Cache::forever('banner_article', $bannerArticle);
        }

        return $next($request);
    }
}
